import { ref, computed } from 'vue'
import { documentApi } from '@/modules/doc/api'
import type { Doc } from '@/modules/doc/types/doc.ts'
import { toast } from '@/utils/message'

/**
 * 文档详情组合式函数
 * 封装文档详情的获取、处理和状态管理
 */
export function useDocDetail() {
  // 响应式状态
  const document = ref<Doc | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const isLoaded = computed(() => !!document.value)
  const hasError = computed(() => !!error.value)

  /**
   * 获取文档详情
   * @param documentId 文档ID
   * @param options 选项配置
   */
  const fetchDocumentDetail = async (
    documentId: string,
    options: {
      showLoading?: boolean
      showError?: boolean
      processContent?: boolean
    } = {}
  ) => {
    const {
      showLoading = true,
      showError = true,
      processContent = true
    } = options

    try {
      if (showLoading) loading.value = true
      error.value = null

      // 调用API获取数据
      const response = await documentApi.getById(documentId)

      // 数据处理逻辑
      if (response.data) {
        document.value = response.data
        
        // 如果需要处理内容（如Markdown解析、图片路径处理等）
        if (processContent && document.value.content) {
          document.value.content = processDocumentContent(document.value.content)
        }
      }

      return document.value
    } catch (err: any) {
      const errorMessage = err.message || '获取文档详情失败'
      error.value = errorMessage
      
      if (showError) {
        toast.error(errorMessage)
      }
      
      throw err
    } finally {
      if (showLoading) loading.value = false
    }
  }

  /**
   * 处理文档内容
   * @param content 原始内容
   */
  const processDocumentContent = (content: string): string => {
    // 处理相对路径图片
    const cdnBaseUrl = (import.meta as any).env?.VITE_CDN_BASE_URL || ''
    content = content.replace(
      /!\[([^\]]*)\]\((?!http)([^)]+)\)/g,
      `![$1](${cdnBaseUrl}/$2)`
    )
    
    // 处理其他内容格式化
    // 可以添加更多处理逻辑
    
    return content
  }

  /**
   * 重新加载文档
   */
  const reloadDocument = async () => {
    if (document.value?.id) {
      await fetchDocumentDetail(document.value.id)
    }
  }

  /**
   * 清空文档数据
   */
  const clearDocument = () => {
    document.value = null
    error.value = null
    loading.value = false
  }

  /**
   * 更新文档标题
   * @param newTitle 新标题
   */
  const updateDocumentTitle = (newTitle: string) => {
    if (document.value) {
      document.value.name = newTitle
    }
  }

  /**
   * 更新文档内容
   * @param newContent 新内容
   */
  const updateDocumentContent = (newContent: string) => {
    if (document.value) {
      document.value.content = newContent
    }
  }

  return {
    // 状态
    document,
    loading,
    error,
    
    // 计算属性
    isLoaded,
    hasError,
    
    // 方法
    fetchDocumentDetail,
    reloadDocument,
    clearDocument,
    updateDocumentTitle,
    updateDocumentContent
  }
}